package com.huyanqi.front.rest.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.huyanqi.core.RetdCodeType;
import com.huyanqi.core.RetdObj;
import com.huyanqi.core.service.impl.BaseFrontServiceImpl;
import com.huyanqi.core.util.MD5Tools;
import com.huyanqi.dao.UserDAO;
import com.huyanqi.entity.User;
import com.huyanqi.front.rest.service.UserRestService;

@Service("UserRestService")
public class UserRestImpl extends BaseFrontServiceImpl<User,Long, UserDAO> implements UserRestService{

	@Override
	public RetdObj<List<User>> getUserList() throws Exception {
		RetdObj<List<User>> retdObj=new RetdObj<List<User>>();
		List<User> users=this.entityDao.executeQuery("SELECT u FROM User u",-1,-1);
		if(users!=null&&users.size()>0){
			retdObj.setCode(RetdCodeType.PASS_OK);
			retdObj.setRealObj(users);
		}else{
			retdObj.setCode(RetdCodeType.PASS_NODATA);
		}
		return  retdObj;
	}

	@Override
	@Resource(name="UserDAO")
	public void setEntityDao(UserDAO entityDao) {
		this.entityDao=entityDao;
	}

	@Override
	public RetdObj<User> regUser(User user) throws Exception {
		RetdObj<User>  obj=new RetdObj<User>();
		//先判断email是否可用
		if(entityDao.executeQuery("FROM User u WHERE u.uEmail = ?", new Object[]{user.getUEmail()}).size()>0){
			//email已被使用
			obj.setCode(RetdCodeType.EX_PARAM);
		}else{
			//email没有使用 再注册
			user.setUPassword(MD5Tools.toMd5(user.getUPassword()));
			user=entityDao.saveEntity(user);
			obj.setRealObj(user); 
			obj.setCode(RetdCodeType.PASS_OK);
		}
		return obj;
	}
	
	@Override
	public RetdObj<User> loginUser(User u) {
		RetdObj<User>  obj=new RetdObj<User>();
		List<User> list = entityDao.executeQuery("FROM User u WHERE u.uEmail = ?", new Object[]{u.getUEmail()});
		if(list.size()>0){
			User user = list.get(0);
			if(user.getUPassword().equals(u.getUPassword())){
				obj.setCode(RetdCodeType.PASS_OK);
				obj.setRealObj(user);
			}else{
				obj.setCode(RetdCodeType.EX_AUTH);
			}
		}else{
			obj.setCode(RetdCodeType.EX_PARAM);
		}
		return obj;
	}
	
	@Override
	public RetdObj<User> getUserByUid(Long uid) {
		RetdObj<User> obj = new RetdObj<User>();
		try{
			User u = entityDao.executeQuery("FROM User WHERE uId = ?", uid).get(0);
			if(u!=null){
				obj.setRealObj(u);
				obj.setCode(RetdCodeType.PASS_OK);
			}else {
				obj.setCode(RetdCodeType.PASS_NODATA);
			}
		}catch (Exception e) {
			e.printStackTrace();
			obj.setCode(RetdCodeType.EX_APP);
		}
		return obj;
	}
	
}
